
package com.zhaoliangji.architecture.ui.page;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.kunminx.architecture.ui.page.DataBindingActivity;
import com.zhaoliangji.architecture.BaseApplication;
import com.zhaoliangji.architecture.R;
import com.zhaoliangji.architecture.data.receiver.NetworkStateManager;
import com.zhaoliangji.architecture.utils.BarUtils;

import java.lang.reflect.Method;

public abstract class BaseActivity extends DataBindingActivity {

    protected final String TAG = this.getClass().getSimpleName();

    private ViewModelProvider mActivityProvider;
    private ViewModelProvider mApplicationProvider;

    private RelativeLayout mLoadingProgress;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

//        setDefaultDisplay();

        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
        BarUtils.setStatusBarLightMode(this, true);

        super.onCreate(savedInstanceState);

        getLifecycle().addObserver(NetworkStateManager.getInstance());

    }



    protected <T extends ViewModel> T getActivityScopeViewModel(@NonNull Class<T> modelClass) {
        if (mActivityProvider == null) {
            mActivityProvider = new ViewModelProvider(this);
        }
        return mActivityProvider.get(modelClass);
    }

    protected <T extends ViewModel> T getApplicationScopeViewModel(@NonNull Class<T> modelClass) {
        if (mApplicationProvider == null) {
            mApplicationProvider = new ViewModelProvider((BaseApplication) this.getApplicationContext(),
                    getAppFactory(this));
        }
        return mApplicationProvider.get(modelClass);
    }

    private ViewModelProvider.Factory getAppFactory(Activity activity) {
        Application application = checkApplication(activity);
        return ViewModelProvider.AndroidViewModelFactory.getInstance(application);
    }

    private Application checkApplication(Activity activity) {
        Application application = activity.getApplication();
        if (application == null) {
            throw new IllegalStateException("Your activity/fragment is not yet attached to "
                    + "Application. You can't request ViewModel before onCreate call.");
        }
        return application;
    }

//    @Override
//    public Resources getResources() {
////        if (ScreenUtils.isPortrait()) {
////            return AdaptScreenUtils.adaptWidth(super.getResources(), 360);
////        } else {
////            return AdaptScreenUtils.adaptHeight(super.getResources(), 640);
////        }
//    }

    protected void toggleSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    protected void openUrlInBrowser(String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    protected void showLongToast(String text) {
        if (TextUtils.isEmpty(text)) text = "未知错误";
        Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
    }

    protected void showShortToast(String text) {
        if (TextUtils.isEmpty(text)) text = "未知错误";
        Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
    }

    protected void showLongToast(int stringRes) {
        showLongToast(getApplicationContext().getString(stringRes));
    }

    protected void showShortToast(int stringRes) {
        showShortToast(getApplicationContext().getString(stringRes));
    }


    protected void toggleLoadingProgress(Boolean show) {
        if (show) {
            showLoadingProgress();
        } else {
            hideLoadingProgress();
        }
    }


    /**
     * 加载进度圈
     */
    protected void showLoadingProgress() {
        Window window = getWindow();
        if (window == null) {
            return;
        }
        ViewGroup decorView = (ViewGroup) window.getDecorView();
        if (decorView != null && !isLoadingProgressShowing()) {
            if (mLoadingProgress == null) {
                mLoadingProgress = (RelativeLayout) LayoutInflater.from(this)
                        .inflate(R.layout.archi_loading_progress_layout, decorView, false);
            }
            mLoadingProgress.setClickable(false);
            if (mLoadingProgress.getParent() == null) {
                decorView.addView(mLoadingProgress);
            }
            mLoadingProgress.requestFocus();
        }
    }

    /**
     * 加载进度圈是否显示
     *
     * @return
     */
    protected boolean isLoadingProgressShowing() {
        return mLoadingProgress != null && mLoadingProgress.getParent() != null;
    }

    /**
     * 加载进度圈隐藏
     */
    protected void hideLoadingProgress() {
        if (mLoadingProgress != null) {
            ViewGroup parent = (ViewGroup) mLoadingProgress.getParent();
            if (parent != null) {
                parent.removeView(mLoadingProgress);
            }
        }
    }


    /**
     * 修改字体大小不随系统设置字体大小而变化
     *
     * @return
     */
    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        if (resources != null) {
            Configuration newConfig = resources.getConfiguration();
            if (newConfig.fontScale != 1) {
                Log.d("TAG", "getResources newConfig.fontScale-->" + newConfig.fontScale);
                newConfig.fontScale = 1;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    Context configurationContext = createConfigurationContext(newConfig);
                    resources = configurationContext.getResources();
                } else {
                    DisplayMetrics displayMetrics = resources.getDisplayMetrics();
                    resources.updateConfiguration(newConfig, displayMetrics);
                }
            }
        }
        return resources;
    }


    /**
     * 获取手机出厂时默认的densityDpi并设置给手机，解决设置显示大小导致布局错乱的问题
     * 在需要用到的activity中的onCreate中调用该方法
     */
    private Point mPoint = new Point();

    protected void setDefaultDisplay() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            Resources resources = getResources();
            if (resources != null) {
                int defaultDisplayDensity = getDefaultDisplayDensity();
                if (mPoint.x == 0 || defaultDisplayDensity == -1) {
                    return;
                }
                Configuration origConfig = resources.getConfiguration();
                DisplayMetrics displayMetrics = resources.getDisplayMetrics();
                int initialDisplayWidth = mPoint.x;//系统默认分辨率
                int curDisplayWidth = displayMetrics.widthPixels;//当前应用分辨率
                double scaling = curDisplayWidth / (initialDisplayWidth * 1.0);//缩放比例 根据分辨率同比缩放
                scaling = scaling <= 0 ? 1 : scaling;
//                Log.e(TAG, "getResources origConfig.densityDpi-->" + origConfig.densityDpi);
//                Log.d(TAG,"getResources displayMetrics.widthPixels-->" + displayMetrics.widthPixels);
//                Log.d(TAG,"getResources displayMetrics.heightPixels-->" + displayMetrics.heightPixels);
//                Logger2.d("getResources defaultDisplayDensity-->" + defaultDisplayDensity);
                origConfig.densityDpi = (int) (defaultDisplayDensity * scaling);//获取手机出厂时默认的densityDpi
//                Logger2.d(TAG, "getResources origConfig.densityDpi-->" + origConfig.densityDpi);
                //createConfigurationContext(origConfig);//不生效，原因不详。。。
                resources.updateConfiguration(origConfig, displayMetrics);
            }
        }
    }

    /**
     * 通过反射获取系统默认的density
     *
     * @return
     */
    private int getDefaultDisplayDensity() {
        try {
            Class clazz = Class.forName("android.view.WindowManagerGlobal");
            Method method = clazz.getMethod("getWindowManagerService");
            method.setAccessible(true);
            Object iwm = method.invoke(clazz);
            Method getInitialDisplayDensity = iwm.getClass().getMethod("getInitialDisplayDensity", int.class);
            Method getInitialDisplaySize = iwm.getClass().getMethod("getInitialDisplaySize", int.class, Point.class);
            getInitialDisplayDensity.setAccessible(true);
            getInitialDisplaySize.setAccessible(true);
            getInitialDisplaySize.invoke(iwm, Display.DEFAULT_DISPLAY, mPoint);
//            Logger.e("getResources point --> " + mPoint.x + " " + mPoint.y);
            Object densityDpi = getInitialDisplayDensity.invoke(iwm, Display.DEFAULT_DISPLAY);
            return (int) densityDpi;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }


}
